<template>
  <div>
    <Row>
      <i-col span="24">
        <Button type="primary" size="large" @click="checkboxSelect">
          {{checkboxSelectStatue?'取消选择':'全选'}}
        </Button>
        <Button type="primary" size="large" @click="confirmDispatch">
          派单
        </Button>
        <Button type="error" size="large" @click="checkRemove">
          撤销
        </Button>
        <Button type="primary" size="large" @click="confirmDispatchNoDriver">
          未指定派单
        </Button>
      </i-col>
    </Row>
    <Row>
      <i-col span="24">
        <Table ref="subOrderTab" :columns="subOrderColumn" border :data="dispatchNotDataClone" style="margin-top: 15px;" height="600"></Table>
      </i-col>
    </Row>
    <xlinkModal v-model="operaModal.confirmDispatchShow" title="派单" className="vertical-center-modal" width="600px;">
      <checkAddressModal v-if="operaModal.confirmDispatchShow" :dispatchDriverInfo="dispatchDriverInfo" :addressList="resAddressList" @dispatch="fleetDispatchDriver"></checkAddressModal>
    </xlinkModal>

    <xlinkModal v-model="operaModal.checkDriverShow" title="派单" className="vertical-center-modal" width="800px;">
      <checkDriverModal v-if="operaModal.checkDriverShow" :dispatchDriverInfo="dispatchDriverInfo" :addressList="resAddressList" :driverList="driverList" @dispatch="fleetDispatchNotDriver"></checkDriverModal>
    </xlinkModal>
  </div>
</template>

<script>
  import { getTruckTypeList } from '@api/backEnd/fleetControl'
  import { assignmentForDriver, assignmentForNotDriverKel, unbindSubOrderNoWithUser } from '@api/backEnd/mainOrder'
  import { getTrainTypeCN } from './trainTypeEnum'
  import checkAddressModal from './checkAddressModal'
  import checkDriverModal from './checkDriverModal'
  import xlinkModal from '@components/modal/xlinkModal'
  import pinyin from '@components/common/pinyin'
  import _ from 'lodash'

  export default {
    name: 'dispatch-not',
    data () {
      let subOrderColumn = [
        {
          type: 'index',
          width: 60
        },
        {
          width: 60,
          align: 'center',
          render: (h, params) => {
            return (<checkbox v-model={params.row.check}></checkbox>)
          }
        },
        {
          title: '火车车种类型',
          ellipsis: 'false',
          width: 150,
          render: (h, params) => {
            let trainType = params.row.trainType
            let trainTypeCN = getTrainTypeCN(trainType)
            return (<span>{trainTypeCN}</span>)
          }
        },
        {
          title: '箱号',
          ellipsis: 'false',
          width: 150,
          key: 'containerNoBody',
          render: (h, params) => {
            let containerNo = params.row.containerNoHead + params.row.containerNoBody
            return (<span>{containerNo}</span>)
          }
        },
        {
          title: '司机',
          ellipsis: 'false',
          width: 400,
          render: (h, params) => {
            let driverName = params.row.driverName
            // let shippingAddress = params.row.shippingAddress
            // let fleetDispatch = params.row.fleetDispatch
            let vif = params.row.check
            if (vif && !driverName) {
              let driverList = this.driverList
              let truckTypeList = this.truckTypeList
              console.log('truckTypeList', truckTypeList)
              return (<auto v-model={params.row.driverId} field="id" label="login_name" on-on-change={(val) => this.selectDriverChange(val, params.row)} search-keys="login_namePy,login_name" dataList={driverList} dropAll={true}
                groupData={truckTypeList} groupField="id" groupLabel="name" groupFilterKeys="type"></auto>)
            } else {
              params.row.driverId = ''
              return (<span></span>)
            }
          }
        },
        {
          title: '发货人',
          ellipsis: 'false',
          key: 'zkfhrmc',
          width: 250
        },
        {
          title: '收货人',
          ellipsis: 'false',
          key: 'zkshrmc',
          width: 250
        },
        {
          title: '品名',
          ellipsis: 'false',
          key: 'zkpmhz0',
          width: 150
        },
        {
          title: '送货地址',
          ellipsis: 'false',
          width: 200,
          key: 'shippingAddress',
          render: (h, params) => {
            return (<span>{params.row.shippingAddress}</span>)
          }
        },
        {
          title: '联系人',
          ellipsis: 'false',
          width: 100,
          key: 'contacts'
        },
        {
          title: '联系人电话',
          ellipsis: 'false',
          width: 150,
          key: 'contactsMobile'
        },
        {
          title: '接取送达费(元)',
          ellipsis: 'false',
          key: 'zkjf018',
          width: 120
        },
        {
          title: '状态',
          ellipsis: 'false',
          width: 80,
          key: '',
          render: (h, params) => {
            return (<span style="color:red">未派单</span>)
          }
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          width: 250,
          render: (h, params) => {
            let voucherImg = params.row.voucherImg
            let viewImg = (<i-button size="small" style="margin-right: 5px;">图片查看</i-button>)
            if (voucherImg) {
              viewImg = (<i-button type="primary" size="small" style="margin-right: 5px;" onClick={() => this.viewDetailImgAction(params.row)}>图片查看</i-button>)
            }
            let btnArray = []
            powerUtil.contains('orderListUnfinishedFleet') && btnArray.push(viewImg)
            return (btnArray)
          }
        }
      ]
      let resAddressList = []
      let resAddress = ''
      let dispatchNotDataClone = []
      let checkboxSelectStatue = false
      let dispatchDriverInfo = {}
      let operaModal = { confirmDispatchShow: false, checkDriverShow: false }
      let truckTypeList = []
      let datas = { subOrderColumn, resAddressList, resAddress, dispatchNotDataClone, checkboxSelectStatue, operaModal, truckTypeList, dispatchDriverInfo }
      return datas
    },
    props: {
      driverList: {
        type: Array,
        default () {
          return []
        }
      },
      addressList: {
        type: Array,
        default () {
          return []
        }
      },
      dispatchNotData: {
        type: Array,
        default () {
          return []
        }
      },
      currentMainOrder: {
        type: Object,
        default () {
          return {}
        }
      }
    },
    computed: {},
    methods: {
      selectRow (selection, row) {
        row.check = true
      },
      /**
       * TODO(未指定派单)
       * @auther zhangQ
       * @date 2018/4/2 12:36
       */
      confirmDispatchNoDriver () {
        let checkData = []
        this.$refs['subOrderTab'].rebuildData.forEach((item) => {
          if (item.check) {
            checkData.push(item)
          }
        })
        if (!(checkData.length > 0)) {
          this.$Notice.warning({
            title: '警告',
            desc: '请选择运单'
          })
          return
        }

        function valit (fild) {
          let currentVal = checkData[0][fild]
          for (let i = 1, counti = checkData.length; i < counti; i++) {
            if (currentVal !== checkData[i][fild]) {
              return false
            } else {
              currentVal = checkData[i][fild]
            }
          }
          return 1
        }

        if (!(checkData.length === 1 || (valit('shippingAddress') && valit('contacts') && valit('contactsMobile')))) {
          this.$Notice.warning({
            title: '警告',
            desc: '选择的地址不一致'
          })
        } else {
          this.dispatchDriverInfo = { shippingAddress: checkData[0].shippingAddress, contacts: checkData[0].contacts, contactsMobile: checkData[0].contactsMobile }
          this.operaModal.checkDriverShow = true
        }
      },
      /**
       * TODO(全选/反选)
       * @auther zhangQ
       * @date 2018/3/27 16:47
       */
      checkboxSelect () {
        if (!this.checkboxSelectStatue) {
          this.$refs['subOrderTab'].rebuildData.forEach((item) => {
            item.check = true
          })
        } else {
          this.$refs['subOrderTab'].rebuildData.forEach((item) => {
            item.check = false
          })
        }
        this.checkboxSelectStatue = !this.checkboxSelectStatue
      },
      selectDriverChange (val, row) {
        row.driverId = val
      },
      /**
       * TODO(指定司机派单)
       * @auther zhangQ
       * @date 2018/3/26 21:10
       */
      fleetDispatchDriver (otherForm) {
        let param = []
        this.$refs['subOrderTab'].rebuildData.forEach((item) => {
          if (item.check && item.driverId) {
            param.push({ mainOrderNo: item.mainOrderNo, subOrderNo: item.orderNo, driverId: item.driverId, address: otherForm.address, contactsMobile: otherForm.mobile, contacts: otherForm.contacts })
          }
        })
        if (param && param.length > 0) {
          let result = param.some((item) => {
            if (!item.driverId || !item.address) {
              return true
            }
          })
          if (result) {
            this.$Message.error('司机和地址必选')
            return
          }
          assignmentForDriver(param).then(res => {
            if (+res.data.isSuccess === 1) {
              this.$Message.success('派单成功')
              this.operaModal.confirmDispatchShow = false
              this.$emit('refreshSource')
            } else {
              this.$Message.error(res.data.res)
            }
          })
        } else {
          this.$Message.error('请选择司机后派单')
        }
      },
      /**
       * TODO(未指定司机)
       * @auther zhangQ
       * @date 2018/4/2 16:23
       */
      fleetDispatchNotDriver (otherForm) {
        let param = []
        this.$refs['subOrderTab'].rebuildData.forEach((item) => {
          if (item.check && otherForm && otherForm.driverIds && otherForm.driverIds.length > 0) {
            param.push({ mainOrderNo: item.mainOrderNo, subOrderNo: item.orderNo, driverId: JSON.stringify(otherForm.driverIds), address: otherForm.address, contactsMobile: otherForm.mobile, contacts: otherForm.contacts })
          }
        })
        if (param && param.length > 0) {
          let result = param.some((item) => {
            if (!item.driverId || !item.address) {
              return true
            }
          })
          if (result) {
            this.$Message.error('司机和地址必选')
            return
          }
          assignmentForNotDriverKel(param).then(res => {
            if (+res.data.isSuccess === 1) {
              this.$Message.success('派单成功')
              this.operaModal.checkDriverShow = false
              this.$emit('refreshSource')
            }
          })
        } else {
          this.$Message.error('请选择一条数据后派单')
        }
      },
      /**
       * TODO(撤销)
       * @auther zhangQ
       * @date 2018/3/27 18:15
       */
      checkRemove (val, row) {
        let param = []
        this.$refs['subOrderTab'].rebuildData.forEach((item) => {
          if (item.check) {
            param.push({ mainOrderNo: item.mainOrderNo, subOrderNo: item.orderNo })
          }
        })
        if (param && param.length === 0) {
          this.$Notice.warning({
            title: '错误',
            desc: '请选择子运单'
          })
          return
        }
        unbindSubOrderNoWithUser(param).then((res) => {
          if (+res.data.isSuccess === 1) {
            this.$Notice.success({
              title: '成功',
              desc: '解绑成功'
            })
            this.$emit('refreshSource')
          }
        })
      },
      // checkListAdd (val, row, index) {
      //   if (val) {
      //     this.checkList.push({ mainOrderNo: row.mainOrderNo, subOrderNo: row.orderNo })
      //   } else {
      //     let index = _.findIndex(this.checkList, { 'subOrderNo': String(row.orderNo) })
      //     if (index >= 0) {
      //       this.checkList.splice(index, 1)
      //     }
      //   }
      // },
      confirmDispatch () {
        let checkData = []
        this.$refs['subOrderTab'].rebuildData.forEach((item) => {
          if (item.check) {
            checkData.push(item)
          }
        })
        if (!(checkData.length > 0)) {
          this.$Notice.warning({
            title: '警告',
            desc: '请选择运单'
          })
          return
        }

        function valit (fild) {
          let currentVal = checkData[0][fild]
          for (let i = 1, counti = checkData.length; i < counti; i++) {
            // checkData[i][fild]
            if (currentVal !== checkData[i][fild]) {
              return false
            } else {
              currentVal = checkData[i][fild]
            }
          }
          return 1
        }

        if (!(checkData.length === 1 || (valit('shippingAddress') && valit('contacts') && valit('contactsMobile')))) {
          this.$Notice.warning({
            title: '警告',
            desc: '选择的地址不一致'
          })
        } else {
          this.dispatchDriverInfo = { shippingAddress: checkData[0].shippingAddress, contacts: checkData[0].contacts, contactsMobile: checkData[0].contactsMobile }
          this.operaModal.confirmDispatchShow = true
        }
      },
      viewDetailImgAction (row) {
        this.$emit('viewDetailImg', row)
      },
      onShow () {
        this.dispatchNotDataClone = _.cloneDeep(this.dispatchNotData)
        this.dispatchNotDataClone.forEach((item) => {
          this.$set(item, 'check', false)
          this.$set(item, 'driverId', '')
        })
        this.resAddressList = []
        this.addressList.forEach((item) => {
          let py = pinyin.codefans_net_CC2PY(item)
          this.resAddressList.push({
            key: item,
            keyPy: py
          })
        })
      },
      getTruckType () {
        getTruckTypeList().then(res => {
          this.truckTypeList = res.data.data
        })
      }
    },
    watch: {
      'dispatchNotData.length' (val, oldVal) {
        this.onShow()
      }
    },
    mounted () {
      this.onShow()
      this.driverList.forEach((item) => {
        let py = pinyin.codefans_net_CC2PY(item.login_name)
        item.login_namePy = py
      })
      this.getTruckType()
    },
    components: { checkAddressModal, xlinkModal, checkDriverModal }
  }
</script>

<style scoped>

</style>
